package com.chx.controller;

import com.chx.dto.RolesDto;
import com.chx.entity.Roles;
import com.chx.result.Result;
import com.chx.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author cp-月入过万
 * @Date 2025/5/29
 * 角色管理
 */
@RestController
@RequestMapping("/admin/role")
@Api(tags = "角色相关接口")
@Slf4j
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 获取所有角色
     * @return
     */
    @ApiOperation(value = "获取所有角色")
    @GetMapping("/list")
    @Cacheable(cacheNames = "roleCache",key = "'list'")
    public Result<List<Roles>> getAllRoles(){
        log.info("获取所有角色");
        List<Roles> roles = roleService.getAllRoles();
        return Result.success(roles);
    }

    /**
     * 新增角色
     */
    @ApiOperation(value = "新增角色")
    @PostMapping
    @CacheEvict(cacheNames = "roleCache",allEntries = true)
    public Result<String> save(@RequestBody RolesDto rolesDto){
        log.info("新增角色");
        roleService.save(rolesDto);
        return Result.success();
    }

    /**
     * 修改角色
     */
    @ApiOperation(value = "修改角色")
    @PutMapping
    @CacheEvict(cacheNames = "roleCache",allEntries = true)
    public Result<String> update(@RequestBody RolesDto rolesDto){
        log.info("修改角色");
        roleService.update(rolesDto);
        return Result.success();
    }

    /**
     * 删除角色
     */
    @ApiOperation(value = "删除角色")
    @DeleteMapping("/{id}")
    @CacheEvict(cacheNames = "roleCache",allEntries = true)
    public Result<String> delete(@PathVariable Long id){
        log.info("删除角色");
        roleService.delete(id);
        return Result.success();
    }

    /**
     * 根据角色id获取角色信息
     */
    @ApiOperation(value = "根据角色id获取角色信息")
    @GetMapping("/{id}")
    @Cacheable(cacheNames = "roleCache",key = "'id_' + #id")
    public Result<Roles> getById(@PathVariable Long id){
        log.info("根据角色id获取角色信息");
        return Result.success(roleService.getById(id));
    }
}
